package com.manager.common.pdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.io.*;

@SuppressWarnings("all")
public class JacobUtils {

    private static final Integer WORD_TO_PDF_OPERAND = 17;
    private static final Integer PPT_TO_PDF_OPERAND = 32;
    private static final Integer EXCEL_TO_PDF_OPERAND = 0;
    private static final int ppSaveAsPDF = 32;
    public static final int WORD_HTML = 8;

    public static void wordToPdf(String sourcePath, String targetPath) {
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            ComThread.InitSTA();
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", false);
            Dispatch docs = app.getProperty("Documents").toDispatch();
            Object[] obj = new Object[]{sourcePath, new Variant(false), new Variant(false), // 是否只读
                    new Variant(false), new Variant("pwd")};
            doc = Dispatch.invoke(docs, "Open", Dispatch.Method, obj, new int[1]).toDispatch();
            // Dispatch.put(doc, "Compatibility", false); //兼容性检查,为特定值false不正确
            Dispatch.put(doc, "RemovePersonalInformation", false);
            Dispatch.call(doc, "ExportAsFixedFormat", targetPath, WORD_TO_PDF_OPERAND); // word保存为pdf格式宏，值为17

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (doc != null) {
                Dispatch.call(doc, "Close", false);
            }
            if (app != null) {
                app.invoke("Quit", 0);
            }
            ComThread.Release();
        }
    }

    public static void pptTopdf(String srcFilePath, String pdfFilePath) throws Exception {
        try {
            ActiveXComponent app = new ActiveXComponent("Powerpoint.Application");
            //app.setProperty("Visible", false);
            Dispatch ppts = app.getProperty("Presentations").toDispatch();

            Dispatch ppt = Dispatch.call(ppts, "Open", srcFilePath, true, // ReadOnly
                    true, // Untitled指定文件是否有标题
                    false// WithWindow指定文件是否可见
            ).toDispatch();

            Dispatch.call(ppt, "SaveAs", pdfFilePath, ppSaveAsPDF);

            Dispatch.call(ppt, "Close");

            app.invoke("Quit");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void excelToPdf(String inFilePath, String outFilePath) throws Exception {
        ActiveXComponent ax = null;
        Dispatch excel = null;
        try {
            ComThread.InitSTA();
            ax = new ActiveXComponent("Excel.Application");
            ax.setProperty("Visible", new Variant(false));
            ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            Dispatch excels = ax.getProperty("Workbooks").toDispatch();

            Object[] obj = new Object[]{inFilePath, new Variant(false), new Variant(false)};
            excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();

            // 转换格式
            Object[] obj2 = new Object[]{new Variant(EXCEL_TO_PDF_OPERAND), // PDF格式=0
                    outFilePath, new Variant(0) // 0=标准 (生成的PDF图片不会变模糊) ; 1=最小文件
            };
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, obj2, new int[1]);

        } catch (Exception es) {
            es.printStackTrace();
            throw es;
        } finally {
            if (excel != null) {
                Dispatch.call(excel, "Close", new Variant(false));
            }
            if (ax != null) {
                ax.invoke("Quit", new Variant[]{});
                ax = null;
            }
            ComThread.Release();
        }

    }

    // txt转pdf
    public static void txtToPdf(String inFilePath, String outFilePath) throws Exception {
        String fontPath = "/conf/simsun.ttf";
        BaseFont bfChinese = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        // BaseFont bfChinese = BaseFont.createFont(BaseFont.TIMES_ROMAN, "#
        // simple 32 0020 0188", true);
        Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
        FileOutputStream out = new FileOutputStream(outFilePath);
        Rectangle rect = new Rectangle(PageSize.A4.rotate());
        Document doc = new Document(rect);
        PdfWriter writer = PdfWriter.getInstance(doc, out);
        doc.open();
        Paragraph p = new Paragraph();
        p.setFont(FontChinese);
        String fileEncode = EncodingDetect.getJavaEncode(inFilePath);
        // System.out.println(fileEncode);
        BufferedReader read = new BufferedReader(
                new InputStreamReader(new FileInputStream(new File(inFilePath)), fileEncode));
        String line = read.readLine();
        while (line != null) {
            // System.out.println(line);
            p.add(line + "\n");
            line = read.readLine();
        }
        read.close();
        doc.add(p);
        doc.close();
    }

    public static String file2Pdf(String resourcePath) throws Exception {
        String suffix = resourcePath.substring(resourcePath.lastIndexOf(".") + 1, resourcePath.length());
        String pdfTargetPath = resourcePath.substring(0, resourcePath.lastIndexOf(".")) + ".pdf";
        File respurceFile = new File(resourcePath);

        if (!respurceFile.exists()) {
            return null;
        }

        try {
            resourcePath = resourcePath.replaceAll("/", "\\\\");
            pdfTargetPath = pdfTargetPath.replaceAll("/", "\\\\");

            if ("doc".equals(suffix) || "docx".equals(suffix)) {
                JacobUtils.wordToPdf(resourcePath, pdfTargetPath);
            } else if ("xls".equals(suffix) || "xlsx".equals(suffix)) {
                JacobUtils.excelToPdf(resourcePath, pdfTargetPath);
            } else if ("ppt".equals(suffix) || "pptx".equals(suffix)) {
                JacobUtils.pptTopdf(resourcePath, pdfTargetPath);
            } else {
                JacobUtils.txtToPdf(resourcePath, pdfTargetPath);
            }

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return null;
        }
        return pdfTargetPath;
    }

    public static void wordToHtml(String docfile, String htmlfile) {
        ActiveXComponent app = new ActiveXComponent("Word.Application");
        System.out.println("*****正在转换...*****");
        try {
            app.setProperty("Visible", new Variant(false));
            Dispatch docs = app.getProperty("Documents").toDispatch();
            Dispatch doc = Dispatch.invoke(
                    docs,
                    "Open",
                    Dispatch.Method,
                    new Object[]{docfile, new Variant(false),
                            new Variant(true)}, new int[1]).toDispatch();
            Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[]{
                    htmlfile, new Variant(WORD_HTML)}, new int[1]);
            Dispatch.call(doc, "Close", new Variant(false));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            app.invoke("Quit", new Variant[]{});
        }
        System.out.println("*****转换完毕********");
    }

	/*public static void parseWordTitle(String filePath, List<File_Book_Marks> books) {

		ActiveXComponent word = new ActiveXComponent("Word.Application");

		word.setProperty("Visible", new Variant(false));

		Dispatch documents = word.getProperty("Documents").toDispatch();

		Dispatch wordFile = Dispatch.invoke(documents, "Open", Dispatch.Method,
				new Object[] { filePath, new Variant(true), new Variant(false) }, new int[1]).toDispatch();

		Dispatch paragraphs = Dispatch.get(wordFile, "Paragraphs").toDispatch();

		int paraCount = Dispatch.get(paragraphs, "Count").getInt();

		for (int i = 0; i < paraCount; ++i) {

			Dispatch paragraph = Dispatch.call(paragraphs, "Item", new Variant(i + 1)).toDispatch();

			int outline = Dispatch.get(paragraph, "OutlineLevel").getInt();

			if (outline <= 9) {

				// System.out.println("大纲等级：" + outline);
				// System.out.println("\n");
				Dispatch paraRange = Dispatch.get(paragraph, "Range").toDispatch();

				// System.out.println("标题名称：" + Dispatch.get(paraRange, "Text").toString());

				int pages = Integer.parseInt(Dispatch.call(paraRange, "information", 1).toString());

				
				 * System.out.println("标题页码：" + pages); System.out.println("\n");
				 

				File_Book_Marks bookMark = new File_Book_Marks();
				bookMark.setPageNum(pages);
				bookMark.setBookMarkName(Dispatch.get(paraRange, "Text").toString());
				bookMark.setOutline(outline);
				System.out.println(outline);
				books.add(bookMark);
			}

		}

		Dispatch.call(wordFile, "Close", new Variant(true));
		Dispatch.call(word, "Quit");
	}*/

    public static void main(String[] args) {
        /*
         * String filePath = "C:\\Users\\ThinkPad\\Desktop\\潮汐.txt"; String htmlPath =
         * "C:\\Users\\ThinkPad\\Desktop\\简历模板.html"; String savePath =
         * "C:\\Users\\ThinkPad\\Desktop"; String pdfPath =
         * "C:\\Users\\ThinkPad\\Desktop\\潮汐.pdf"; // String
         * content=readWordToHtml(filePath,htmlPath,true); //
         * System.out.println(content); try { // String content
         * =PoiUtil.getHtml(filePath, "简历模板.doc", savePath); //
         * System.out.println(content); txtToPdf(filePath, pdfPath); } catch (Exception
         * e) { // TODO Auto-generated catch block e.printStackTrace(); }
         */
        //String filePath = "C:\\Users\\Luhj\\Desktop\\WEB三维显示软件技术协议-v1.9.doc";
        JacobUtils.wordToHtml("E:\\360MoveData\\Users\\liuhj\\Desktop\\d4d3116ea7164cf99259165c9b78cd28.docx","E:\\360MoveData\\Users\\liuhj\\Desktop\\1.html");
    }
}
